<template>
  <div class="form-edit-box">
    <el-form
      ref="form"
      :model="formData"
      :rules="rules"
      label-width="100px"
      :size="layoutStore.defaultFormItemSize"
    >
      <el-form-item label="受委托人" prop="delegateUsers">
        <user-select
          v-model="formData.delegateUsers"
          :multiple="true"
          :clearable="true"
          :collapseTags="false"
          placeholder="请选择受委托人"
          style="width: 100%"
        />
      </el-form-item>
      <el-form-item label="委托流程" prop="processDefinitionKeys">
        <flow-select
          v-model="formData.processDefinitionKeys"
          :multiple="true"
          :clearable="true"
          :collapseTags="false"
          placeholder="未选择委托流程默认全部流程进行委托"
          style="width: 100%"
        />
      </el-form-item>
      <el-form-item label="委托范围" prop="delegateScope">
        <el-select
          v-model="formData.delegateScope"
          :multiple="true"
          :clearable="true"
          :collapseTags="false"
          placeholder="请选择委托范围"
          style="width: 100%"
        >
          <el-option
            v-for="item in delegateScopeOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="开始时间" prop="startTime">
        <el-date-picker
          v-model="formData.startTime"
          type="datetime"
          placeholder="开始时间"
          style="width: 100%"
          value-format="YYYY-MM-DD HH:mm:ss"
        />
      </el-form-item>
      <el-form-item label="结束时间" prop="endTime">
        <el-date-picker
          v-model="formData.endTime"
          type="datetime"
          placeholder="结束时间"
          style="width: 100%"
          value-format="YYYY-MM-DD HH:mm:ss"
        />
      </el-form-item>
      <el-form-item label="委托说明" prop="memo">
        <el-input v-model="formData.memo" type="textarea" :rows="3" placeholder="请输入委托说明" />
      </el-form-item>
    </el-form>
    <div class="dialog-footer">
      <el-button @click="onCancel">取消</el-button>
      <el-button type="primary" @click="onSubmit" :loading="submitting">确定</el-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue';
import { ElMessage } from 'element-plus';
import { useLayoutStore } from '@/store';
import { ANY_OBJECT } from '@/types/generic';
import { DialogProp } from '@/components/Dialog/types';
import { FlowDelegateUserController } from '@/api/flow';
import { FlowDelegateUser } from '@/types/upms/delegate';
import UserSelect from '@/components/UserSelect/index.vue';
import FlowSelect from '@/components/FlowSelect/index.vue';
import { useThirdParty } from '@/components/thirdParty/hooks';
import { ThirdProps } from '@/components/thirdParty/types';

const enum DelegateScope {
  // 用户
  USER = 'user',
  // 部门
  DEPT = 'dept',
  // 岗位
  POST = 'post',
  // 部门岗位
  DEPT_POST = 'dept_post',
  // 角色
  ROLE = 'role',
}

const layoutStore = useLayoutStore();

interface IProps extends ThirdProps {
  rowData?: ANY_OBJECT;
  // 当使用Dialog.show弹出组件时，须定义该prop属性，以便对dialog进行回调
  dialog?: DialogProp<ANY_OBJECT>;
}

const props = defineProps<IProps>();
const { thirdParams, onCloseThirdDialog } = useThirdParty(props);

const emit = defineEmits(['success', 'cancel']);
const form = ref();
const submitting = ref(false);

const formData = reactive<FlowDelegateUser>({
  id: undefined,
  delegateUsers: undefined,
  processDefinitionKeys: undefined,
  delegateScope: undefined,
  startTime: undefined,
  endTime: undefined,
  memo: undefined,
});

const dialogParams = computed(() => {
  return {
    rowData: props.rowData || thirdParams.rowData || {},
  };
});

const delegateScopeOptions = [
  { label: '用户', value: DelegateScope.USER },
  { label: '部门', value: DelegateScope.DEPT },
  { label: '岗位', value: DelegateScope.POST },
  { label: '部门岗位', value: DelegateScope.DEPT_POST },
  { label: '角色', value: DelegateScope.ROLE },
];

const rules = {
  delegateUsers: [{ required: true, message: '请选择委托人', trigger: 'change' }],
  delegateScope: [{ required: true, message: '请选择委托范围', trigger: 'change' }],
  startTime: [{ required: true, message: '请选择开始时间', trigger: 'change' }],
  endTime: [{ required: true, message: '请选择结束时间', trigger: 'change' }],
};

const initFormData = () => {
  if (dialogParams.value.rowData) {
    console.log(dialogParams.value.rowData);
    // 处理委托人数组
    const delegateUsers =
      dialogParams.value.rowData.delegateUsers?.split(',').filter(Boolean) || [];

    // 处理流程定义键数组
    const processDefinitionKeys =
      dialogParams.value.rowData.processDefinitionKeys?.split(',').filter(Boolean) || [];

    // 处理委托范围数组
    const delegateScope =
      dialogParams.value.rowData.delegateScope?.split(',').filter(Boolean) || [];

    Object.assign(formData, {
      ...dialogParams.value.rowData,
      delegateUsers,
      processDefinitionKeys,
      delegateScope,
    });
  }
};

const onSubmit = () => {
  form.value.validate((valid: boolean) => {
    if (valid) {
      submitting.value = true;
      console.log(formData.delegateUsers);
      const params = {
        flowDelegateUserDto: {
          ...formData,
          delegateUsers: Array.isArray(formData.delegateUsers)
            ? formData.delegateUsers.join(',')
            : formData.delegateUsers,
          processDefinitionKeys: Array.isArray(formData.processDefinitionKeys)
            ? formData.processDefinitionKeys.join(',')
            : formData.processDefinitionKeys,
          delegateScope: Array.isArray(formData.delegateScope)
            ? formData.delegateScope.join(',')
            : formData.delegateScope,
        },
      };

      const apiCall = formData.id
        ? FlowDelegateUserController.updateDelegateUser(params)
        : FlowDelegateUserController.addDelegateUser(params);

      apiCall
        .then(() => {
          ElMessage.success('保存成功');
          if (props.dialog) {
            props.dialog.submit({});
          } else {
            onCloseThirdDialog(true);
          }
        })
        .catch(e => {
          console.warn(e);
        })
        .finally(() => {
          submitting.value = false;
        });
    }
  });
};

const onCancel = () => {
  if (props.dialog) {
    props.dialog.cancel();
  }
};

onMounted(() => {
  initFormData();
});
</script>

<style lang="scss" scoped>
.form-edit-box {
  .dialog-footer {
    margin-top: 20px;
    text-align: right;
  }

  .form-item-label {
    display: flex;
    align-items: center;
  }
}
</style>
